<!DOCTYPE html>
<html  lang="zh-CN" >
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, maximum-scale=5, viewport-fit=cover">
    <title>ajax的了解 | 在路上</title>
    <meta name="description" content="了解ajax">
<meta property="og:type" content="article">
<meta property="og:title" content="ajax的了解">
<meta property="og:url" content="http://www.lushunming.com.cn/2016/04/19/web/2016-04-19-%E4%BA%86%E8%A7%A3ajax/index.html">
<meta property="og:site_name" content="在路上">
<meta property="og:description" content="了解ajax">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2016-04-18T16:00:00.000Z">
<meta property="article:modified_time" content="2019-11-24T07:17:53.641Z">
<meta property="article:author" content="machine">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="ajax">
<meta name="twitter:card" content="summary">

    
    <link rel="icon" href="/images/favicon.ico" type="image/x-icon">

    
<link rel="stylesheet" href="/css/common.min.css">



    
    
    
        <link href="//cdn.jsdelivr.net/npm/gitalk@1.4.0/dist/gitalk.min.css" rel="stylesheet">
    
    
        <link href="//cdn.jsdelivr.net/npm/lightgallery.js@1.1.3/dist/css/lightgallery.min.css" rel="stylesheet">
    
    
    
<link rel="stylesheet" href="/css/iconfont.min.css">

    
<meta name="generator" content="Hexo 5.1.1"></head>

    <body>
        <header class="header header-fixture">
    <div class="profile-search-wrap flex sm:block">
        
        
        <div class="profile sm:text-center md:px-1 lg:px-3 sm:pb-4 sm:pt-6">
            <a id="avatar" role="link" href="https://www.lushunming.com.cn" class="inline-block lg:w-16 lg:h-16 w-8 h-8 m-2" target="_self" rel="noopener" rel="noreferrer" >
                <img src="/images/avatar.jpg" class="rounded-full" alt="avatar">
            </a>
            <h2 id="name" class="hidden lg:block">lushunming</h2>
            <h3 id="title" class="hidden xl:block">前码农</h3>
            
            <small id="location" class="hidden lg:block">
                <i class="iconfont icon-map-icon"></i>
                泰州
            </small>
            
        </div>
        
        
<div class="search flex-1 flex lg:inline-block sm:hidden lg:px-4 lg:mt-2 lg:mb-4 lg:w-full">
    <form id="search-form" class="my-auto flex-1 lg:border lg:border-solid lg:border-gray-200">
        <div class="input-group table bg-gray-100 lg:bg-white w-full">
            <input id="search-input" type="text" placeholder="搜索" class="inline-block w-full bg-gray-100 lg:bg-white">
            <span class="table-cell">
                <button name="search tigger button" disabled>
                    <i class="iconfont icon-search m-2"></i>
                </button>
            </span>
        </div>
    </form>
        
<script id="search-teamplate" type="text/html" data-path="/content.json">
    <div>
        <div class="search-header bg-gray-400">
            <input id="actual-search-input" model="keyword" ref="input" class="inline-block w-full h-10 px-2 py-1" placeholder="搜索" type="text">
        </div>
        <div class="search-result bg-gray-200">
            {{#each searchPosts}}
            <a href="/{{ path }}" class="result-item block px-2 pb-3 mb-1 pt-1 hover:bg-indigo-100">
                <i class="iconfont icon-file"></i>
                <h1 class="result-title inline font-medium text-lg">{{ title }}</h1>
                <p class="result-content text-gray-600 text-sm">{{{ text }}}</p>
            </a>
            {{/each}}
        </div>
    </div>
</script>

</div>


        <button name="menu toogle button" id="menu-toggle-btn" class="block sm:hidden p-3" role="button" aria-expanded="false">
            <i class="iconfont icon-hamburger"></i>
        </button>
    </div>
    <nav id="menu-nav" class="hidden sm:flex flex-col">
        
        
            <div class="menu-item menu-home" role="menuitem">
                <a href="/.">
                    <i class="iconfont icon-home" aria-hidden="true"></i>
                    <span class="menu-title">首页</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-archives" role="menuitem">
                <a href="/archives">
                    <i class="iconfont icon-archive" aria-hidden="true"></i>
                    <span class="menu-title">归档</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-categories" role="menuitem">
                <a href="/categories">
                    <i class="iconfont icon-folder" aria-hidden="true"></i>
                    <span class="menu-title">分类</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-tags" role="menuitem">
                <a href="/tags">
                    <i class="iconfont icon-tag" aria-hidden="true"></i>
                    <span class="menu-title">标签</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-repository" role="menuitem">
                <a href="/repository">
                    <i class="iconfont icon-project" aria-hidden="true"></i>
                    <span class="menu-title">项目</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-links" role="menuitem">
                <a href="/links">
                    <i class="iconfont icon-friend" aria-hidden="true"></i>
                    <span class="menu-title">友链</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-about" role="menuitem">
                <a href="/about">
                    <i class="iconfont icon-cup" aria-hidden="true"></i>
                    <span class="menu-title">关于</span>
                </a>
            </div>
        
        
<div class="social-links flex sm:flex-col lg:hidden mt-5">
    
        <span class="social-item text-center">
            <a target="_blank" rel="noopener" href="https://github.com/lushunming">
                <i class="iconfont social-icon icon-github"></i>
                <span class="menu-title hidden lg:inline">menu.github</span>
            </a>
        </span>
    
        <span class="social-item text-center">
            <a href="/atom.xml">
                <i class="iconfont social-icon icon-rss"></i>
                <span class="menu-title hidden lg:inline">menu.rss</span>
            </a>
        </span>
    
</div>


    </nav>
</header>

        <section class="main-section">
            
    <main class="flex-1 px-4 py-12 md:px-5 lg:px-8 lg:py-4 relative min-h-screen">
    

    <article class="content article article-archives article-type-list" itemscope="">
        <header class="article-header">
            
    
        <h1 class="article-title text-lg" itemprop="name">
            ajax的了解
        </h1>
    



            <p class="article-meta mb-3 text-xs">
                <span class="article-date">
    <i class="iconfont icon-calendar-check"></i>
	<a href="/2016/04/19/web/2016-04-19-%E4%BA%86%E8%A7%A3ajax/" class="article-date">
	  <time datetime="2016-04-18T16:00:00.000Z" itemprop="datePublished">4月 19</time>
	</a>
</span>

                
    <span class="article-category">
    <i class="iconfont icon-folder"></i>
    <a class="article-category-link" href="/categories/web/">web</a>
  </span>


                
    <span class="article-tags">
    <i class="iconfont icon-tag"></i>
    <a class="article-tag-none-link" href="/tags/ajax/" rel="tag">ajax</a>, <a class="article-tag-none-link" href="/tags/javascript/" rel="tag">javascript</a>
  </span>


                <span class="_partial/post-comment"><i class="icon icon-comment"></i>
                    <a href="/2016/04/19/web/2016-04-19-%E4%BA%86%E8%A7%A3ajax/#comments" class="article-comment-link">
                        评论
                    </a>
                </span>
                

            </p>
        </header>
        <div class="marked-body article-body">
            <h1>ajax的了解</h1>
<p>虽然每天都在使用ajax，但是我发现我好像对于ajax一点都不了解，他到底是什么？我们每天都在用的jquery的封装，他就是一个黑盒子，方便但是我们却不知道他的本身。我们每天也人云亦云，然而其实我们连ajax到底是什么都不知道。今天我们就来揭开他的神秘面纱。</p>
<p>记得我刚学习web时，觉得很神奇，一个ajax请求就能返回一串json数据。原来我到今天才发现我错了。ajax英文叫做 <code>asynchronous JavaScript and XML</code>，用中文翻译就是异步的javascript和xml技术，那么我们发现我们现在用的貌似和xml没有半毛钱关系。确实，以前xml是前后台之间的数据交互形式，但是现在都是以json来传输数据，所以ajax中的xml技术不是必须的，现在基本被json取代，所以其实我们现在用的是<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/AJAJ">ajaj</a>,这就是ajax的由来。</p>
<p>我们在使用时都知道ajax最厉害的是异步操作，当你发送一个请求时，当没有返回时，浏览器会继续执行其他的任务，而不会挂起等待，这就是异步的好处，当然也带来一些问题。比如我之前写一个东西（忘记是什么了），要做几个ajax请求，他们之间是有先后顺序的，当时我想javascript是按顺序执行的，于是我就把它们按照顺序写下来，发现每次请求的顺序都不一样。。。现在我终于找到了答案。</p>
<p>原生的ajax是依赖于XMLHttpRequest 对象，在比较老的IE5 、6中是依赖于 ActiveXObject对象，所以要兼容性就这么写：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr;</span><br><span class="line"><span class="keyword">if</span> (<span class="built_in">window</span>.XMLHttpRequest)</span><br><span class="line">  &#123;<span class="comment">// code for IE7+, Firefox, Chrome, Opera, Safari</span></span><br><span class="line">  xhr=<span class="keyword">new</span> XMLHttpRequest();</span><br><span class="line">  &#125;</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">  &#123;<span class="comment">// code for IE6, IE5</span></span><br><span class="line">  xhr=<span class="keyword">new</span> ActiveXObject(<span class="string">&quot;Microsoft.XMLHTTP&quot;</span>);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>下面便是发送请求：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">  xhr.open(<span class="string">&#x27;get&#x27;</span>, <span class="string">&#x27;send-ajax-data.php&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 检测ajax的请求状态</span></span><br><span class="line">xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> DONE = <span class="number">4</span>; <span class="comment">// readyState 4 means the request is done.</span></span><br><span class="line">    <span class="keyword">var</span> OK = <span class="number">200</span>; <span class="comment">// status 200 is a successful return.</span></span><br><span class="line">    <span class="keyword">if</span> (xhr.readyState === DONE) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xhr.status === OK) &#123;</span><br><span class="line">            alert(xhr.responseText); <span class="comment">// &#x27;This is the returned text.&#x27;</span></span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            alert(<span class="string">&#x27;Error: &#x27;</span> + xhr.status); <span class="comment">// An error occurred during the request.</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发送请求</span></span><br><span class="line">xhr.send(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>
<p>在ajax中onreadystatechange会被调用五次，因为<code>xhr.readyState</code>会有五个值，</p>
<ul>
<li>0: 请求未初始化</li>
<li>1: 服务器连接已建立</li>
<li>2: 请求已接收</li>
<li>3: 请求处理中</li>
<li>4: 请求已完成，且响应已就绪</li>
</ul>
<p>每一次值变化的时候，onreadystatechange就会被触发，我们也就是在其中穿插回调方法。</p>
<p>请求的回应可以通过<code>xhr.responseText</code>和<code>xhr.responseXML</code>获取，responseText是获取string类型的响应，responseXML是获取xml类型的响应。</p>
<p>到此我们对ajax也有了一个简单的认识，有种豁然开朗的感觉。在这里不得不说有时候有不明白的地方需要自己去查找答案，一切便豁然开朗。这里我推荐使用维基百科，维基百科的解释更加权威，详细。大家也可以去我的个人博客查看（ <a target="_blank" rel="noopener" href="http://coding.lushunming.top/">http://coding.lushunming.top/</a> 或者是  <a target="_blank" rel="noopener" href="http://github.lushunming.top/">http://github.lushunming.top/</a>  ），个人博客的排版字体更加优美。</p>

        </div>
        
<blockquote class="copyright">
    <p><strong>本文链接 : </strong><a class="permalink" href="http://www.lushunming.com.cn/2016/04/19/web/2016-04-19-%E4%BA%86%E8%A7%A3ajax/">http://www.lushunming.com.cn/2016/04/19/web/2016-04-19-了解ajax/</a></p>
    <p><strong>This article is available under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener noreferrer">Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)</a> License</strong></p>
</blockquote>


    </article>
    
    <section id="comments">
        

        
    </section>


    

</main>


<aside style="" id="sidebar" class="aside aside-fixture">
    <div class="toc-sidebar">
        <nav id="toc" class="article-toc">
            <h3 class="toc-title">文章目录</h3>
            <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">ajax的了解</span></a></li></ol>
        </nav>
    </div>
</aside>





        </section>
        <footer class="hidden lg:block fixed bottom-0 left-0 sm:w-1/12 lg:w-1/6 bg-gray-100 z-40">
    
    <div class="footer-social-links">
        
            <a target="_blank" rel="noopener" href="https://github.com/lushunming">
                <i class="iconfont icon-github"></i>
            </a>
        
            <a href="/atom.xml">
                <i class="iconfont icon-rss"></i>
            </a>
        
    </div>
    
    
</footer>

        <div id="mask" class="hidden mask fixed inset-0 bg-gray-900 opacity-75 z-40"></div>
        <div id="search-view-container" class="hidden shadow-xl"></div>
        
<script src="/js/dom-event.min.js"></script>

<script src="//cdn.jsdelivr.net/npm/yox@1.0.0-alpha.121/dist/standard/prod/yox.min.js"></script>


<script src="/js/search.min.js"></script>


    <script src="//cdn.jsdelivr.net/npm/gitalk@1.5.2/dist/gitalk.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>
<script type="text/javascript">
    var gitalk = new Gitalk({
        clientID: 'd76d74420825181b7018',
        clientSecret: '8b9c3676695fa33d6b10d9697a96ef27c8301930',
        repo: 'blog-comment',
        owner: 'lushunming',
        admin: ['lushunming'],
        id: md5(location.pathname),
        distractionFreeMode: true
    })
    gitalk.render('comments')
</script>



    <script src="//cdn.jsdelivr.net/npm/lightgallery.js@1.1.3/dist/js/lightgallery.min.js"></script>
    
<script src="/js/light-gallery.min.js"></script>





    </body>
</html>
